from sanic import Sanic, response, websocket
import asyncio

from view.conn import bp1


app = Sanic(__name__)
app.blueprint(bp1)


@app.route('/test')
async def test(request):
    return response.text('success')


@app.middleware('response')
async def add(request, response):
    response.headers["Access-Control-Allow-Origin"] = '*'
    response.headers["Access-Control-Allow-Methods"] = "POST,GET,OPTIONS"
    response.headers["Access-Control-Expose-Headers"] = "Set-Cookie,token"
    response.headers["Access-Control-Allow-Headsanic_demo/main/usr.py:16ers"] = "Set-Cookie,token"
    response.headers["Access-Control-Allow-Credentials"] = "true"


@app.websocket('/test1')
async def test1(request, ws):
    # websocket
    try:
        while True:
            await ws.send('success!')
            await asyncio.sleep(2)
            # data = await ws.recv()
            # print(data)
            # if data == '5':     # 收到的数据是字符串！！！！
            #     break
    finally:
        print(1)


@app.websocket('/test2')
async def test2(request, ws):
    while True:
        print(123)
        a = [1, 2]
        await ws.send(str(a))
        await asyncio.sleep(5)


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=9001)
